<script setup lang="ts">
import { nextTick } from 'vue'
import { NANOID } from '@own-basic-component/util'
import { NConfigProvider, dateZhCN, zhCN } from 'naive-ui'
import { sendOp } from '@own-basic-component/buried'
import loginRequest from '~/api/login'
import { clearToken, getAutoToken, getToken, setToken } from '~/util/once/token-util'
import { handleRsa } from '~/util/once/rsa-util'
import { useUserStore } from '~/store/user-store'

// 页面是否可见
const visible = ref<boolean>(false)

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

onMounted(() => {
  // 获取token信息
  const token = getToken()
  new Promise((resolve) => {
    if (!token) {
      resolve(false)
    }
    else {
      loginRequest.check().then(async (data) => {
        const flag = data.data
        if (flag) {
          // 获取登录用户的信息
          loginRequest.info().then((data) => {
            userStore.setUser(data.data)
            // 设置自动登录成功的日志
            sendOp({
              actionName: '会话维持成功',
            })
          })
          resolve(true)
        }
        else {
          // 设置自动登录信息
          const autoToken = getAutoToken()
          if (autoToken) {
            // 执行自动登录
            const key = NANOID(16)
            // 加密密码
            const { data: rsaKey } = await loginRequest.rsa(key)
            const newPassword = handleRsa(autoToken, rsaKey)
            return await loginRequest.autoLogin(newPassword, key).then((data) => {
              // 设置登录后的信息
              setToken(data.data)
              // 获取登录用户的信息
              loginRequest.info().then((data) => {
                userStore.setUser(data.data)
                // 设置自动登录成功的日志
                sendOp({
                  actionName: '自动登录成功',
                })
              })
              resolve(true)
            })
          }
          else {
            resolve(false)
          }
        }
      })
    }
  }).then((flag) => {
    nextTick(async () => {
      if (flag) {
        if (route.path === '/login')
          await router.push('/manage/project')
      }
      else {
        clearToken()
        await router.push('/login')
      }
      // 显示主内容
      visible.value = true
    })
  })
})
</script>

<template>
  <NConfigProvider :locale="zhCN" :date-locale="dateZhCN">
    <div text="gray-700 dark:gray-200" h-100vh overflow-hidden font-sans>
      <router-view v-if="visible" />
    </div>
  </NConfigProvider>
</template>
